// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <utility>

#include <pollux/core/plan_node.h>
#include <pollux/exec/output_buffer_manager.h>
#include <pollux/tool/trace/operator_replayer_base.h>

namespace kumo::pollux::tool::trace {

/// Concurrently gets all partitioned buffer content (vec<IOBuf>) for every
/// partition.
void consumeAllData(
    const std::shared_ptr<exec::OutputBufferManager>& bufferManager,
    const std::string& taskId,
    uint32_t numPartitions,
    melon::Executor* executor,
    melon::ThreadPoolExecutor* consumerExecutor,
    std::function<void(uint32_t, std::unique_ptr<melon::IOBuf>)> consumer);

/// The replayer to replay the traced 'PartitionedOutput' operator.
class PartitionedOutputReplayer final : public OperatorReplayerBase {
 public:
  using ConsumerCallBack =
      std::function<void(uint32_t, std::unique_ptr<melon::IOBuf>)>;

  PartitionedOutputReplayer(
      const std::string& traceDir,
      const std::string& queryId,
      const std::string& taskId,
      const std::string& nodeId,
      VectorSerde::Kind serdeKind,
      const std::string& operatorType,
      const std::string& driverIds,
      uint64_t queryCapacity,
      melon::Executor* executor,
      const ConsumerCallBack& consumerCb = [](auto partition, auto page) {});

  RowVectorPtr run(bool /*unused*/) override;

 private:
  core::PlanNodePtr createPlanNode(
      const core::PlanNode* node,
      const core::PlanNodeId& nodeId,
      const core::PlanNodePtr& source) const override;

  const core::PartitionedOutputNode* const originalNode_;
  const VectorSerde::Kind serdeKind_;
  const std::shared_ptr<exec::OutputBufferManager> bufferManager_{
      exec::OutputBufferManager::getInstanceRef()};
  const std::unique_ptr<melon::Executor> executor_{
      std::make_unique<melon::CPUThreadPoolExecutor>(
          std::thread::hardware_concurrency(),
          std::make_shared<melon::NamedThreadFactory>("Driver"))};
  const ConsumerCallBack consumerCb_;
  std::unique_ptr<melon::CPUThreadPoolExecutor> consumerExecutor_;
};
} // namespace kumo::pollux::tool::trace
